
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include <cstdint>
class MessageFrame
{
public:
    // 构造函数
    MessageFrame(const std::string &jsonStr)
    {
        if (jsonStr.size() > 1024)
        {
            throw std::invalid_argument("JSON string exceeds 1024 bytes");
        }

        data = jsonStr;
        totalPacketsCount = (data.size() + MAX_PACKET_SIZE - 1) / MAX_PACKET_SIZE;

        // 分割数据为小包
        for (size_t i = 0; i < totalPacketsCount; ++i)
        {
            size_t start = i * MAX_PACKET_SIZE;
            size_t length = std::min(MAX_PACKET_SIZE, data.size() - start);
            packets.push_back(data.substr(start, length));
        }
    }

    // 获取指定索引的小包，TLV 格式
    std::vector<uint8_t> getPacket(size_t index) const
    {
        if (index >= totalPacketsCount)
        {
            throw std::out_of_range("Packet index out of range");
        }

        const std::string &packetData = packets[index];
        size_t packetSize = packetData.size();

        // 构造 TLV 数据包
        std::vector<uint8_t> tlvPacket;
        tlvPacket.push_back(0xAA);                                    // T: Type 固定为 0xAA
        tlvPacket.push_back(static_cast<uint8_t>(totalPacketsCount)); // L: 总包数
        tlvPacket.push_back(static_cast<uint8_t>(index));             // L: 当前包索引
        tlvPacket.push_back(static_cast<uint8_t>(packetSize));        // L: 当前数据包大小

        // V: 数据部分
        tlvPacket.insert(tlvPacket.end(), packetData.begin(), packetData.end());
        return tlvPacket;
    }

    // 获取总包数
    size_t totalPackets() const
    {
        return totalPacketsCount;
    }

private:
    static constexpr size_t MAX_PACKET_SIZE = 60; // 每包最大数据大小

    std::string data;                 // 原始数据
    std::vector<std::string> packets; // 分割后的小包
    size_t totalPacketsCount;         // 总包数
};